#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <pthread.h>

typedef void (*func_t)(void *);

class Thread
{
public:
    typedef enum
    {
        NEW = 0,
        RUNNING,
        EXIT
    } ThreadStatus;

    Thread(int num, func_t func, void *args) : _tid(0), _status(NEW), _func(func), _args(args)
    {
        char name[128];
        snprintf(name, sizeof(name), "thread-%d", num);
        _name = name;
    }

    ~Thread()
    {
    }

    int status() { return _status; }

    std::string name() { return _name; }

    pthread_t threadid()
    {
        if (_status == RUNNING)
            return _tid;
        else
            return 0;
    }

    static void *RunHelper(void *args) // 由于本函数是静态成员函数，线程调用时还需要外部传this指针进来
    {
        std::cout << "this is RunHelper" << std::endl;
        Thread *ts = (Thread *)args; // 强转恢复this指针
        (*ts)();
    }

    void operator()()
    {
        if (_func != nullptr)
            _func(_args);
    }
    void run()
    {
        int n = pthread_create(&_tid, nullptr, RunHelper, this);
        if (n != 0)
            exit(1);
        //std::cout << "thread create success" << std::endl;
        _status = RUNNING;
    }

    void join()
    {
        int n = pthread_join(_tid, nullptr);
        if (n != 0)
        {
            std::cout << n << std::endl;
            std::cerr << "main thread join thread " << _name << " error" << std::endl;
        }
    }

private:
    pthread_t _tid;
    std::string _name;
    func_t _func;
    void *_args;
    ThreadStatus _status;
};
